package com.ejuornal.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.ejuornal.bean.Board;
import com.ejuornal.bean.PerPeriodical;
import com.ejuornal.bean.PerPeriodicalDetail;
import com.ejuornal.bean.PerPeriodicalSub;
import com.ejuornal.bean.Periodical;
import com.ejuornal.bean.UserExt;
import com.ejuornal.service.BoardService;
import com.ejuornal.service.PerPeriodicalDetailService;
import com.ejuornal.service.PerPeriodicalService;
import com.ejuornal.service.PeriodicalService;
import com.ejuornal.service.SubscribeService;
import com.ejuornal.service.UserExtService;
import com.ejuornal.springutil.SpringUtil;
import com.google.gson.Gson;

public class PerPeriodicalAction extends BaseAction<PerPeriodical> {
	private static final long serialVersionUID = 1L;
	private PerPeriodicalService perPeriodicalService;
	private SubscribeService subscribeService;
	private PerPeriodical perPeriodical;
	private Map<String, Object> dataMap = new HashMap<String, Object>();
	private String value;
	private List<Board> boards;
	private List<PerPeriodical> perPeriodicals;
	private BoardService boardService;
	
	public String find_1th_byperi() {
		int id = Integer.parseInt(value);
		if(id == -1){
			return ERROR;
		}
		dataMap.clear();
		perPeriodical = perPeriodicalService.findNewPerPeriodical(id, "-1");
		dataMap.put("perPeriodicalId", perPeriodical.getPerPeriodicalId());
		boards = boardService.findByPeriodicalId(id);
		dataMap.put("boards", boards);
		return SUCCESS;
	}
	
	/**
	 * 每期期刊的发布，同时创建下一期期刊
	 * @author syb
	 * @return
	 */
	public String publishPerPeriodical() {
		//如果该期期刊没有文章的话，则不发表期刊
		if(perPeriodical.getPerPeriodicalId() != 0) {
			
			
			//发布期刊，及修改未通过的期刊，
			perPeriodical.setStatus("0"); // 每次发布、修改未通过期刊时，都将状态由“-1”改成“0”
			perPeriodical.setCheckResult(null);
			perPeriodicalService.update(perPeriodical);
			
			if("2".equals(value)) {	//"2" 表示修改未通过的期刊
				return "success";
			}
			// 发布一期期刊后，再生成下期期刊
			PerPeriodical perPeriodicalNew = new PerPeriodical();
			perPeriodicalNew.setPeriodicalId(perPeriodical.getPeriodicalId());
			perPeriodicalNew.setNumber(perPeriodical.getNumber()+1);
			perPeriodicalNew.setStatus("-1"); // 每次发布期刊后都自动生成下期期刊，状态设为-1
			perPeriodicalService.add_2(perPeriodicalNew);
		} else {
			value = "没有文章不能发布期刊";
		}
		
		return "success";
	}
	
	/**
	 * 主编审核每期期刊
	 * @author syb
	 * @return
	 */
	public String checkPerPeriodical() {
		//审核每期期刊，更改被审核期刊的状态
		perPeriodicalService.updateStatus(perPeriodical, value);

		//主编审核后，修改t_periotidal表中的出版时间（pubDate）字段的值
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		PeriodicalService periodicalService = (PeriodicalService)SpringUtil.getBean("periodicalService");
		//修改发布时间
		periodicalService.updatePubDate(sdf.format(new Date()), perPeriodical.getPeriodicalId());
		
		//把新发表的期刊保存到表中，发送给用户邮箱
		if("1".equals(value)) {
			PerPeriodicalSub pps = new PerPeriodicalSub();
			pps.setPeriodicalId(perPeriodical.getPeriodicalId());
			pps.setPerPeriodicalid(perPeriodical.getPerPeriodicalId());
			perPeriodicalService.add(pps);
		}
		
		return "success";
	}

	public String findById() {
		//每期期刊的ID号，用来得到该期期刊的版块及版块里的文章
		int perPeriodicalId = perPeriodical.getPerPeriodicalId();
		
		//得到期刊的ID号
		int periodicalId = perPeriodical.getPeriodicalId();
		if(periodicalId == 0) {
			//根据每期期刊的ID查询得到该期刊的信息
			PerPeriodical perPeriodical2 = perPeriodicalService.findById(perPeriodicalId);
			periodicalId = perPeriodical2.getPeriodicalId();
			perPeriodical = perPeriodical2;
		}
		
		//根据期刊的ID得到期刊的详细信息
		Periodical periodical = ((PeriodicalService) SpringUtil.getBean("periodicalService")).findById(periodicalId);
		
		//得到期刊信息并封装到Request中
		super.setRequestAttribute("periodical", periodical);
		
		//通过期刊中的userId查询主编
		UserExt editorChief = ((UserExtService)SpringUtil.getBean("userExtService")).findByUserId(periodical.getUserId());
		super.setRequestAttribute("editorChief", editorChief);
		
		//得到期刊的Id，用来得到期刊的编辑、编委等信息
//		int periodicalId = periodical.getPeriodicalId();
		PerPeriodicalDetailService perPeriodicalDetailService = (PerPeriodicalDetailService) SpringUtil.getBean("perPeriodicalDetailService");
		
		//得到期刊的编辑
		List<PerPeriodicalDetail> editors = perPeriodicalDetailService.findEditor(periodicalId);
		super.setRequestAttribute("editors", editors);
		
		//得到期刊的编委
		List<PerPeriodicalDetail> editorCommits = perPeriodicalDetailService.findEditorCommit(periodicalId);
		super.setRequestAttribute("editorCommits", editorCommits);
		
		//根据每期期刊的ID号得到该期期刊的版块及每个版块的文章
		List<PerPeriodicalDetail> perPeriodicalDetails = perPeriodicalDetailService.findBoardArtical(perPeriodicalId);
		super.setRequestAttribute("perPeriodicalDetails", perPeriodicalDetails);
		
		perPeriodicals = perPeriodicalService.findPerPeriodicalNumbers(periodicalId, "1");
		
		if("2".equals(value)) {
			return "check"; //跳转到主编审核期刊页面
		} else if("3".equals(value)) {
			return "edit";
		} else {
			int userId = super.getUserIdBySession();
			if(userId != -1 && subscribeService.isSubscribe(userId, periodicalId) != 0) {
				value = "1";	//1表示已订阅
			} else {
				value = "0";	//0表示未订阅
			}
			
			return "success";
		}
	}
	
	/**
	 * 查询每期期刊的版块及每个版块的文章，ajax
	 * @author syb
	 */
	public void findPerPeriodicalArticle() {
		perPeriodical = perPeriodicalService.findNewPerPeriodical(Integer.parseInt(value), "-1");
		PerPeriodicalDetailService perPeriodicalDetailService = (PerPeriodicalDetailService)SpringUtil.getBean("perPeriodicalDetailService");
		List<PerPeriodicalDetail> perPeriodicalDetails = perPeriodicalDetailService.findBoardArtical(perPeriodical.getPerPeriodicalId());

		Gson gson = new Gson();
		String data = gson.toJson(perPeriodicalDetails);
		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.reset();
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter pw = null;
		
		try {
			pw = response.getWriter();
			pw.print(data);
			pw.flush();
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 查询该期期刊的上期和下期的期刊ID号，使用ajax请求
	 * @author syb
	 */
	public void findUpNextPerPeriodical () {
		//得到每期期刊的Service
		perPeriodicalService = (PerPeriodicalService) SpringUtil.getBean("perPeriodicalService");
		//根据每期期刊的ID查询得到该期刊的信息
		
		perPeriodical = perPeriodicalService.findById(perPeriodical.getPerPeriodicalId());
		//得到期刊的ID号
		int periodicalId = perPeriodical.getPeriodicalId();
		
		//该期期刊的期刊号
		int number = perPeriodical.getNumber();
		
		//得到期刊的所有期刊号
		perPeriodicals = perPeriodicalService.findPerPeriodicalNumbers(periodicalId, "1");
		
		//用来记录上、下一期的ID号
		int upPerPeriodicalId = 0;
		int nextPerPeriodicalId = 0;
		
		for(int i=perPeriodicals.size(); i>0; i--) {
			if(number == perPeriodicals.get(i-1).getNumber()) {
				if(i>1 && i<perPeriodicals.size()){
					//得到上期的ID号
					upPerPeriodicalId = perPeriodicals.get(i).getPerPeriodicalId();
					//得到下期的ID号
					nextPerPeriodicalId = perPeriodicals.get(i-2).getPerPeriodicalId();

					break;
				} else if (i == 1 && i != perPeriodicals.size()) {
					//得到上期的ID号
					upPerPeriodicalId = perPeriodicals.get(i).getPerPeriodicalId();

					break;
				} else if (i == perPeriodicals.size() && i != 1) {
					//得到下期的ID号
					nextPerPeriodicalId = perPeriodicals.get(i-2).getPerPeriodicalId();

					break;
				}
			}
		}
		
		//得到上期下期的ID号并封装到List中
		List<Integer> upNextIds = new ArrayList<Integer>();
		upNextIds.add(upPerPeriodicalId);
		upNextIds.add(nextPerPeriodicalId);
		
		//响应ajax的请求
		Gson son = new Gson();
		String aaaString = son.toJson(upNextIds);	//将封装有上下期期刊号的List用Gson转换成String
		HttpServletResponse res = ServletActionContext.getResponse();   
		res.reset();	//清除首部的空白行
		res.setContentType("text/html;charset=utf-8");   
		PrintWriter pw;
		try {
			pw = res.getWriter();
			pw.print(aaaString);
			pw.flush();   
			pw.close();  
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 得到某期刊已经发布的所有期刊，ajax
	 * @return
	 */
	public String findByPeriodicalId() {
		List<PerPeriodical> perPeriodicals = perPeriodicalService.findPerPeriodicalNumbers(Integer.parseInt(value), "1");
		dataMap.clear();
		dataMap.put("perPeriodicals", perPeriodicals);
		
		return "success";
	}
	
	/**
	 * Desription 根据登录用户的ID查询不同状态的每期期刊
	 * @author syb
	 */
	public String findByUserIdPPStatus() {
		String url = "perPeriodical/perPeriodicalByUserIdPPStatus?value=" + value + "&";
		perPeriodicalService = (PerPeriodicalService)SpringUtil.getBean("perPeriodicalService");
		pages = perPeriodicalService.findByUserIdPPStatus((page-1)*10, url, super.getUserIdBySession(), value);
		
		return "success";
	}
	
	/**
	 * Desription 查询某一期刊已经发布的所有期刊
	 * @author syb
	 */
	public String findByPeriodicalIdPStatus() {
		String url = "perPeriodical/perPeriodicalByPeriodicalId?perPeriodical.periodicalId=" + perPeriodical.getPeriodicalId() + "&";
		perPeriodicalService = (PerPeriodicalService)SpringUtil.getBean("perPeriodicalService");
		pages = perPeriodicalService.findByPeriodicalIdPPStatus((page-1)*10, url, perPeriodical.getPeriodicalId(), "1");
		
		return "success";
	}
	
	/**
	 * 得到编辑所属期刊未通过的每期期刊，也可扩展查不同状态的期刊
	 * @return
	 */
	public String findPerPerEditor() {
		perPeriodicals = perPeriodicalService.findPerPerEditor(super.getUserIdBySession(), "2");
		
		return "success";
	}
	
	public List<PerPeriodical> getPerPeriodicals() {
		return perPeriodicals;
	}

	public void setPerPeriodicals(List<PerPeriodical> perPeriodicals) {
		this.perPeriodicals = perPeriodicals;
	}

	public PerPeriodical getPerPeriodical() {
		return perPeriodical;
	}

	public void setPerPeriodical(PerPeriodical perPeriodical) {
		this.perPeriodical = perPeriodical;
	}
	
	public PerPeriodicalService getPerPeriodicalService() {
		return perPeriodicalService;
	}
	@Resource(name="perPeriodicalService")
	public void setPerPeriodicalService(PerPeriodicalService perPeriodicalService) {
		this.perPeriodicalService = perPeriodicalService;
	}
	public Map<String, Object> getDataMap() {
		return dataMap;
	}
	public void setDataMap(Map<String, Object> dataMap) {
		this.dataMap = dataMap;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
	
	public List<Board> getBoards() {
		return boards;
	}

	public void setBoards(List<Board> boards) {
		this.boards = boards;
	}
	
	public BoardService getBoardService() {
		return boardService;
	}
	@Resource(name="boardService")
	public void setBoardService(BoardService boardService) {
		this.boardService = boardService;
	}

	public SubscribeService getSubscribeService() {
		return subscribeService;
	}

	public void setSubscribeService(SubscribeService subscribeService) {
		this.subscribeService = subscribeService;
	}
}
